package com.haojii.jdo.basic;
import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.haojii.jdo.utils.PMF;

@SuppressWarnings("serial")
public class KeyTestServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		System.out.println("1.0 Create and persist UserLong with @PrimaryKey: Long id");
		UserLong userLong = new UserLong("name1",UserLong.class.getName());
		pm.makePersistent(userLong);
		
		System.out.println("1.1 Query UserLong with getObjectById");
	    UserLong tmpUserLong = null;
	    Long id = userLong.getId();
	    tmpUserLong = pm.getObjectById(UserLong.class, id);
	    System.out.println("userLong==tmpUserLong?"+(userLong==tmpUserLong));
	    
	    System.out.println("1.2 Query UserLong with name1");
	    tmpUserLong = null;
	    Query query = pm.newQuery(UserLong.class); 
	    query.setFilter("name == nameParam"); 
	    query.setOrdering("date desc"); 
	    query.declareParameters("String nameParam");
	    try { 
	        List<UserLong> results = (List<UserLong>) query.execute("name1"); 
	        System.out.println("All UserLong size:"+results.size());
	        if (results.iterator().hasNext()) { 
	            for (UserLong e : results) { 
	            	tmpUserLong = e;
	                System.out.println(" "+e);
	            } 
	        } else { 
	        	System.out.println("1.2 Query get empty result");
	        } 
	    } finally { 
	        query.closeAll(); 
	    }
	    
	    if (tmpUserLong != null)
	    {
	    	System.out.println("1.3 Update the searched result[0] UserLong with name1->NAME!");
	    	System.out.println("userLong==tmpUserLong?"+(userLong==tmpUserLong));
	    	tmpUserLong.setName("NAME!");
	    	pm.makePersistent(tmpUserLong);
	    }
	    
	    System.out.println("1.4 Delete UserLong with name1");
	    System.out.println(" ->"+userLong);
	    pm.deletePersistent(userLong);

	    
	    query = pm.newQuery(UserLong.class); 
	    System.out.println("All UserLong size:"+((List<UserLong>) query.execute()).size());
		resp.getWriter().println("Hello, world");
	}
}
